package com.pushtalk.service;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.log4j.Logger;

import com.pushtalk.Config;
import com.pushtalk.MainPush;
import com.pushtalk.dao.BussDAO;
import com.pushtalk.entity.BussNotify;
import com.pushtalk.utils.HttpUtility;
import com.pushtalk.utils.IMUtil;
import com.pushtalk.utils.LogUtil;

/**
 * 业务提醒数据推送服务
 * get和 Post方式的代码未完成，
 * 将来可添加一个params表和params配置表，用来定制需要推送的字段（作为http提交的参数）
 * 
 * @author wx
 *
 */
public class PushTask extends java.util.TimerTask {

	Logger logger = Logger.getLogger(PushTask.class);

	@Override
	public void run() {

		try {
			PushData();
		} catch (Exception e) {

			e.printStackTrace();
			LogUtil.error(logger, e.getMessage());
		}
	}

	private void PushData() {

		List<BussNotify> AllNotifyList = BussDAO.getAllNotify();

		for (BussNotify bn : AllNotifyList) {

			String id = bn.getId();
			String busstype = bn.getBussType();
			String context = bn.getSubject();

			if (context != null) {
				Push(bn);
			}

			BussDAO.DeleteNotify(id, busstype);
		}
	}

	private void Push(BussNotify bn) {
		try {
			if (Config.PushMode.equals("talk")) {
				IMUtil.SendToIM(bn);
			}
			
			if (Config.PushMode.equals("get")) {
		        String requestURL = "http://XXXX";
		        try {
		            HttpUtility.sendGetRequest(requestURL);
		            String[] response = HttpUtility.readMultipleLinesResponeGBK();
		            for (String line : response) {
		                System.out.println(line);
		            }
		        } catch (IOException e) {
		            e.printStackTrace();
					LogUtil.error(logger, e.getMessage());
		        }
		        HttpUtility.disconnect();
			}
			
			if (Config.PushMode.equals("post")) {
		        Map<String, String> params = new HashMap<String, String>();
		        String requestURL = "http://XXXX?";
		        params.put("q", "java");
		        params.put("qqq", "java222");
		         
		        try {
		            HttpUtility.sendPostRequest(requestURL, params);
		            String[] response = HttpUtility.readMultipleLinesRespone();
		            for (String line : response) {
		                System.out.println(line);
		            }
		        } catch (IOException e) {
		            e.printStackTrace();
					LogUtil.error(logger, e.getMessage());
		        }
		        HttpUtility.disconnect();
			}
			
			logger.info("推送数据：" + bn.getBussType() +" -- " + bn.getUsername());
			
		} catch (Exception e) {
			LogUtil.error(logger, e.getMessage());
			e.printStackTrace();
		}
	}

	public static String getUUID() {
		String s = UUID.randomUUID().toString();
		// 去掉“-”符号
		return s.substring(0, 8) + s.substring(9, 13) + s.substring(14, 18) + s.substring(19, 23) + s.substring(24);
	}


}